using System;
using MonoDevelop.Components.Commands;
using Gtk;
using MonoDevelop.Ide;
using Mono.TextEditor;
using MonoDevelop.Refactoring;
using System.Reflection;

namespace MonoDevelop.CtrlClick
{
	public class CtrlClickCommand : CommandHandler
	{
		const uint LEFT_BUTTON = 1;
		
		protected override void Run ()
		{
			base.Run ();
			var parentWindow = IdeApp.Workbench.RootWindow;
			IdeApp.Workbench.DocumentOpened += HandleDocumentOpened;
		}

		void HandleDocumentOpened (object sender, MonoDevelop.Ide.Gui.DocumentEventArgs e)
		{
			var parentWindow = e.Document.ActiveView.Control as Container;
			if (parentWindow == null)
				return;
			
			var child = parentWindow.Children [0] as Container;
			if (child == null)
				return;
			
			if (child.Children [0] != null) {
				child.Children [0].ButtonReleaseEvent += HandleButtonReleaseEvent;
			}
		}

		void HandleButtonReleaseEvent (object o, ButtonReleaseEventArgs args)
		{
			if (!(args.Event.Button == LEFT_BUTTON 
				&& args.Event.Type == Gdk.EventType.ButtonRelease 
				&& ((args.Event.State & Gdk.ModifierType.ControlMask) == Gdk.ModifierType.ControlMask)))
				return;

			MethodInfo methodInfo = typeof(GotoDeclarationHandler)
				.GetMethod ("Run", 
				            BindingFlags.Instance | BindingFlags.NonPublic, 
				            null,
				            new Type[] { typeof(object) },
							null
				);
			if (methodInfo == null)
				return;
			
			methodInfo.Invoke (new GotoDeclarationHandler (), new object[] { null });
		}

		protected override void Update (CommandInfo info)
		{
			base.Update (info);
			info.Enabled = true;
		}
	}
}
